/**
 * 证书管理
 */


layui.define(['table', 'form'], function(exports){
  var $ = layui.$
      , admin = layui.admin
      , setter = layui.setter
  ,view = layui.view
  ,table = layui.table
  ,form = layui.form;

  //证书管理
  table.render({
    elem: '#LAY-cert-manage'
      , url: setter.baseConfig.apiHost + '/api/certificate/getpagingcertificates'
      , method: 'post'
      , contentType: "application/json"
      , headers: { //通过 request 头传递
          Authorization: 'Bearer ' + layui.data(setter.tableName)[setter.request.tokenName]
      }
      , parseData: function (res) { // res 即为原始返回的数据
          return {
              "code": res.errorCode, // 解析接口状态
              "msg": res.errorMessage, // 解析提示文本
              "count": res.data.totalCount, // 解析数据长度
              "data": res.data.entities // 解析数据列表
          };
      }
    ,cols: [[
        { type: 'numbers', fixed: 'left' }
        , { field: 'id', title: 'Id', hide: true }
        , { field: 'createdTime', title: '创建时间', minWidth: 170 }
        , { field: 'certId', title: '证书ID', minWidth: 200 }
        , { field: 'domainName', title: '域名', minWidth: 220 }
        , { field: 'domainNameTypeStr', title: '域名类型', templet: '#domainNameTypeTpl', minWidth: 90 }
        , { field: 'statusStr', title: '证书状态', minWidth: 90 }
        , { field: 'issuedTime', title: '签发时间', minWidth: 170 }
        , { field: 'expiredTime', title: '到期时间', minWidth: 170 }
        ,{title: '操作', width: 280, align:'center', fixed: 'right', toolbar: '#table-cert-webuser'}
    ]]
    ,page: true
    ,limit: 30
    ,height: 'full-320'
    ,text: '对不起，加载出现异常！'
  });

    //依据用户身份显示和隐藏列
    $.ajax({
        url: setter.baseConfig.apiHost + '/api/user/getloginuserinfo' //实际使用请改成服务端真实接口
        , type: 'post'
        , contentType: "application/json"
        //, data: JSON.stringify(field)
        , beforeSend: function (xhr) {
            xhr.setRequestHeader("Authorization", 'Bearer ' + layui.data(setter.tableName)[setter.request.tokenName]);
        }
        , success: function (res) {
            if (res.errorCode != '00000') {
                layer.msg(res.errorMessage, {
                    offset: '15px'
                    , icon: 2
                    , time: 3000
                });
                return false;
            }

            var role = res.data.role;
            if (role != 'ADMIN') {
                // 同时设置多列的显示或隐藏
                table.hideCol('LAY-cert-manage', [{
                    field: 'certId',
                    hide: true
                }, {
                    field: 'statusStr',
                    hide: true
                }]);
            }
        }
    });
  
  //工具条
  table.on('tool(LAY-cert-manage)', function(obj){
    var data = obj.data;
    if(obj.event === 'del'){
        layer.confirm('证书删除后不可恢复，请谨慎操作', { icon: 3, title: '确定要删除证书吗？'}, function (index) {
            $.ajax({
                url: setter.baseConfig.apiHost + '/api/certificate/remove?id=' + data.id
                , type: 'get'
                , contentType: "application/json"
                //, data: JSON.stringify(data)
                , beforeSend: function (xhr) {
                    xhr.setRequestHeader("Authorization", 'Bearer ' + layui.data(setter.tableName)[setter.request.tokenName]);
                }
                , success: function (res) {
                    if (res.errorCode != '00000') {
                        layer.msg(res.errorMessage, {
                            offset: '15px'
                            , icon: 2
                            , time: 3000
                        });

                        return false;
                    }

                    //登入成功的提示与跳转
                    layer.msg('删除成功', {
                        offset: '15px'
                        , icon: 1
                        , time: 1000
                    });

                    layui.table.reload('LAY-cert-manage'); //重载表格
                    layer.close(index); //执行关闭
                }
            });
        });
    } else if(obj.event === 'edit'){
      admin.popup({
        title: '编辑证书'
        ,area: ['500px', '450px']
          , id: 'LAY-popup-cert-add'
          , success: function (layero, index) {
              view(this.id).render('cert/certmanageform', data).done(function(){
            form.render(null, 'layuiadmin-form-dnsauthadmin');
            
            //提交
            form.on('submit(LAY-dnsauth-front-submit)', function(data){
                var field = data.field; //获取提交的字段

                //提交 Ajax 成功后，关闭当前弹层并重载表格
                $.ajax({
                    url: setter.baseConfig.apiHost + '/api/dnsauth/update' //实际使用请改成服务端真实接口
                    , type: 'post'
                    , contentType: "application/json"
                    , data: JSON.stringify(field)
                    , beforeSend: function (xhr) {
                        xhr.setRequestHeader("Authorization", 'Bearer ' + layui.data(setter.tableName)[setter.request.tokenName]);
                    }
                    , success: function (res) {
                        if (res.errorCode != '00000') {
                            layer.msg(res.errorMessage, {
                                offset: '15px'
                                , icon: 2
                                , time: 3000
                            });

                            return false;
                        }

                        //登入成功的提示与跳转
                        layer.msg('修改成功', {
                            offset: '15px'
                            , icon: 1
                            , time: 1000
                        });

                        layui.table.reload('LAY-cert-manage'); //重载表格
                        layer.close(index); //执行关闭
                    }
                });
            });
          });
        }
      });
    } else if (obj.event === 'view') {
        var idxViewCert= admin.popup({
            title: '查看证书'
            , area: ['500px', '450px']
            , id: 'LAY-popup-cert-view'
            , success: function (layero, index) {
                view(this.id).render('cert/viewcertform', data).done(function () {
                    console.log(data);
                    form.render(null, 'layuiadmin-form-viewcert');

                    //查看证书
                    table.render({
                        elem: '#LAY-cert-his'
                        , url: setter.baseConfig.apiHost + '/api/certificate/getpagingcertdetails'
                        , method: 'post'
                        , contentType: "application/json"
                        , headers: { //通过 request 头传递
                            Authorization: 'Bearer ' + layui.data(setter.tableName)[setter.request.tokenName]
                        }
                        , where: { certApplyId: data.id }
                        , parseData: function (res) { // res 即为原始返回的数据
                            return {
                                "code": res.errorCode, // 解析接口状态
                                "msg": res.errorMessage, // 解析提示文本
                                "count": res.data.totalCount, // 解析数据长度
                                "data": res.data.entities // 解析数据列表
                            };
                        }
                        , cols: [[
                            { type: 'numbers', fixed: 'left' }
                            , { field: 'id', title: 'Id', hide: true }
                            , { field: 'createdTime', title: '更新时间', minWidth: 200 }
                            , { field: 'operateType', title: '操作类型', minWidth: 150 }
                            , { field: 'certId', title: '证书ID', minWidth: 300 }
                            , { field: 'sha1', title: 'SHA1', minWidth: 350 }
                            , { field: 'statusStr', title: '证书状态', minWidth: 100 }
                            , { field: 'issuedTime', title: '签发时间', minWidth: 200 }
                            , { field: 'expiredTime', title: '到期时间', minWidth: 200 }
                        ]]
                        , page: true
                        , limit: 30
                        , height: 'full-320'
                        , text: '对不起，加载出现异常！'
                    });
                });
            }
        });
        layer.full(idxViewCert);
    } else if (obj.event === 'download') {//下载证书
        layer.confirm('确定要下载证书吗?', { icon: 1, title: '下载证书' }, function (index) {
            $.ajax({
                url: setter.baseConfig.apiHost + '/api/certificate/download?id=' + data.id
                , type: 'GET'
                //, contentType: "application/json"
                //, data: JSON.stringify(data)
                , beforeSend: function (xhr) {
                    xhr.setRequestHeader("Authorization", 'Bearer ' + layui.data(setter.tableName)[setter.request.tokenName]);
                }
                , success: function (result) {
                    var a = document.createElement('a');
                    a.style.display = 'none';
                    a.href = setter.baseConfig.apiHost + '/api/certificate/download?id=' + data.id;
                    //a.download = 'filename'; // 你可以在这里设置下载文件的名称
                    document.body.appendChild(a);
                    a.click();
                    setTimeout(function () {
                        a.remove();
                    }, 100);

                    //layui.table.reload('LAY-cert-manage'); //重载表格
                    layer.close(index); //执行关闭
                }
            });
        });
    }
  });

  exports('cert', {})
});